package pablo.developer;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class NuevoUsuario extends Activity {
	
	public String name="",surname="",nick="", password="", secretQuestion="",secretAnswer="",address="",zipCode="",city="",state="",country="",email="",telephone="",sipAddress="";
	EditText nameUsuario,surnameUsuario, nickUsuario,passwordUsuario, secretQuestionUsuario,secretAnswerUsuario,addressUsuario,zipCodeUsuario,cityUsuario,stateUsuario,countryUsuario;
    EditText emailUsuario,telephoneUsuario,sipAddressUsuario;
    TextView nombreResultado;
    Button btInsertar;
	Usuario usuario;
	int idUser;
	boolean encontrado;
	
	private static final String URL_BASE = "http://10.0.2.2:8080/PFCServlets/DatosUsuario";
	public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 setContentView(R.layout.nuevousuario);
	        
	        Bundle bundle  = getIntent().getExtras();
	        if (bundle!=null){
	        	
	        	SetUI();
	        	nameUsuario.setText(bundle.getString("name"));
	        	surnameUsuario.setText(bundle.getString("surname"));
	        	secretQuestionUsuario.setText(bundle.getString("secretQuestion"));
	        	secretAnswerUsuario.setText(bundle.getString("secretAnswer"));
	        	addressUsuario.setText(bundle.getString("address"));
	        	zipCodeUsuario.setText(bundle.getString("zipCode"));
	        	cityUsuario.setText(bundle.getString("city"));
	        	stateUsuario.setText(bundle.getString("state"));
	        	countryUsuario.setText(bundle.getString("country"));
	        	emailUsuario.setText(bundle.getString("email"));
	        	telephoneUsuario.setText(bundle.getString("telephone"));
	        	sipAddressUsuario.setText(bundle.getString("sipAddress"));
	        	
	        	
	        }
	        else{
	        	SetUI();
	        }
	       
		}
		public void SetUI(){
			nameUsuario = (EditText)findViewById(R.id.nombre_usuario);
			surnameUsuario= (EditText)findViewById(R.id.apellidos_usuario);
			nickUsuario=(EditText)findViewById(R.id.nick_usuario);
			passwordUsuario=(EditText)findViewById(R.id.password_usuario);
			secretQuestionUsuario=(EditText)findViewById(R.id.secretQuestion_usuario);
			secretAnswerUsuario=(EditText)findViewById(R.id.secretAnswer_usuario);
			addressUsuario=(EditText)findViewById(R.id.address_usuario);
			zipCodeUsuario=(EditText)findViewById(R.id.zipCode_usuario);
			cityUsuario=(EditText)findViewById(R.id.city_usuario);
			stateUsuario=(EditText)findViewById(R.id.state_usuario);
			countryUsuario=(EditText)findViewById(R.id.country_usuario);
			emailUsuario=(EditText)findViewById(R.id.email_usuario);
			telephoneUsuario=(EditText)findViewById(R.id.telephone_usuario);
			sipAddressUsuario=(EditText)findViewById(R.id.sipAddress_usuario);
			btInsertar=(Button)findViewById(R.id.insertar);
			
		}
		public void insertar(View v){
			updateDatos();
			new HTTPServiceClient().execute(URL_BASE);
			
			
		}
		public void updateDatos(){
		 	name=nameUsuario.getText().toString();
		    surname=surnameUsuario.getText().toString();
		    nick=nickUsuario.getText().toString();
		    password=passwordUsuario.getText().toString();
		    secretQuestion=secretQuestionUsuario.getText().toString();
		    secretAnswer=secretAnswerUsuario.getText().toString();
		    address=addressUsuario.getText().toString();
		    zipCode=zipCodeUsuario.getText().toString();
		    state=stateUsuario.getText().toString();
		    city=cityUsuario.getText().toString();
		    country=countryUsuario.getText().toString();
		    email=emailUsuario.getText().toString();
		    telephone=telephoneUsuario.getText().toString();
		    sipAddress=sipAddressUsuario.getText().toString();
	}
	private void showResultConversion(Usuario result) {
		
			boolean encontrado = result.getEncontrado();
			if (!encontrado){
				Toast toast1 =Toast.makeText(getApplicationContext(),"Usuario creado correctamente", Toast.LENGTH_LONG);
		        toast1.show();
				Intent mainIntent = new Intent(NuevoUsuario.this,InicioSesion.class);
		        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        NuevoUsuario.this.startActivity(mainIntent);
		       
		        
			}
			else{
				Intent mainIntent = new Intent(NuevoUsuario.this,NuevoUsuario.class);
				Bundle bundle     = new Bundle();
			 	bundle.putString("name", name);
			 	bundle.putString("surname", surname);
			 	bundle.putString("secretQuestion", secretQuestion);
			 	bundle.putString("secretAnswer", secretAnswer);
			 	bundle.putString("address", address);
			 	bundle.putString("state", state);
			 	bundle.putString("zipCode", zipCode);
			 	bundle.putString("city", city);
			 	bundle.putString("country", country);
			 	bundle.putString("email", email);
			 	bundle.putString("telephone", telephone);
			 	bundle.putString("sipAddress", sipAddress);
			 	mainIntent.putExtras(bundle);
		        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        NuevoUsuario.this.startActivity(mainIntent);
		        Toast toast1 =Toast.makeText(getApplicationContext(),"El usuario ya existe en nuestra base de datos" +
		        		" por favor introduzca otro nombre de Usuario", Toast.LENGTH_LONG);
			    toast1.show();
		        
		        
			}
	}
	
	public class HTTPServiceClient extends AsyncTask<String, Void, Usuario>{
    	final ProgressDialog dialog = new ProgressDialog(NuevoUsuario.this);

    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.setMessage("Conectando con la base de datos de Uvipool...");
		    dialog.show();
		}

		
    	@Override
		protected Usuario doInBackground(String... url) {
			
    		Usuario result;
			try 
			{
				result = getResult(url[0]);
			} 
			catch (Exception e) 
			{
				result = Usuario.getEmpty();
				e.printStackTrace();
			}
			return result;
		}

    	protected void onPostExecute(Usuario result) {
			dialog.dismiss();
			showResultConversion(result);
			super.onPostExecute(result);
		    NuevoUsuario.this.finish();
		}
		
		private Usuario getResult(String url) throws ClientProtocolException, IOException, JSONException
		{
			UsuarioInputs inputs = new UsuarioInputs(name,surname,nick, password, secretQuestion, secretAnswer,address, zipCode, city, state, country, email, telephone, sipAddress);
			JSONObject inputsJson = new JSONObject(inputs.getInputMap());
			String jsonString = HttpUtils.urlContentPost(url, "usuarioInputs", inputsJson.toString());
			Gson gson = new Gson();
			Usuario infor = gson.fromJson(jsonString, Usuario.class);
			return infor;
			
		}
    }
}
